$(document).ready(function(){
    /*string_url = document.URL.split("/");
    if(string_url[3]=="forms"){
        window.onbeforeunload = function(e) {
            return 'You will lose any unsaved edits';
        };
    }*/
    /******FORM BUILDER********/
    /*ftc  = Function To Call.
     *Get ftc of the object
     */
    //global variables
    objectId = 1;
    
    $(".objects").live("click",function(){
        ftc = $(this).attr("ftc")
        $.post("/ajax/setObject/",{ftc:ftc,objectId:objectId},function(data){
            $(".mainContent").append(data);
            $(".datepicker").datepicker();
            // Animate field created to the form
            $('html, body').animate({
                    scrollTop: $(".mainContent").offset().top
                });
        })
        objectId++;
    });
    
    //tooltip for objects
    $('.objects, .log').tooltip();
    $( "#drag" ).sortable({
        revert: true,
    });
    //click the object
    startIdOfAppend = 1
    $(".setObject").live("click",function(){
        //variable declaration
        master_id = $(this).attr("master-id");
        fieldtypes = ["textbox","checkbox","dropdown","radio","textarea","selectmany","upload","datepicker",
                          "linebreak","linebreak","fullname","datetimepicker","website","email","timepicker","fulladdress"];
        flabel = "";fz = "";flayout = "";choices = "";options = "";nf = "";pdc = "";lb_desc=""; //variable for field settings tab
        object = $(this).attr("object-identifier"); //field or object class
        objectType = $(this).attr("object-type"); //type of field or object
        
        fieldsize_selected = $("."+object).attr("fieldsize_selected"); //for fieldsize to be selected
        showFieldObject_id = $("."+object).attr("showFieldObject_id"); //for field option to be viewed by either admin only or user and admin
        require_check = $("."+object).attr("require_check"); // for require options
        flayout_var = $("."+object).attr("flayout_id"); // for layout options
        nameFormat_id = $("."+object).attr("nf_id"); //for name format
        //clearing the field
        $(".fieldLabel").val(null) //for label
        
        $("."+objectType+master_id).each(function(){
           startIdOfAppend++; //for checkbox and radio, selectmany and dropdown choices
        })
        //for active state of the objects
        span_id = this.id; //id of active state
        
        $(".setObject").each(function(){
            //changing the css
            if(span_id==this.id){
                $("#"+span_id).css({
                    "background-color":"#c4d9ff",
                })
                $("#"+span_id).removeClass("borderDashed");
                $("#head").addClass("borderDashed");
                $("#close"+master_id).css("display","inline-block");
            }else{
                //deactivate the object
                $("#"+this.id).css({
                    "background-color":"#FFF"
                })
                //add class for having a border dashed on hover
                $("#"+this.id).addClass("borderDashed");
                
            }
        });
        
        //deactivate the form header
        $(".setObjectForm").css({
            "background-color":"#FFF"
        });
        //for form settings
        $(".formList").removeClass("active");
        $(".editAddfield").removeClass("active");
        $(".editFieldsetting").addClass("active");
        
        //activate the fieldsettings tab
        $(".addfield").removeClass("active");
        $(".formsetting").removeClass("active");
        $(".workflowSettings").removeClass("active");
        $(".fieldsettings").addClass("active");
        
        //for changing the field label
        label_id = $(this).attr("label-object");
        $(".fieldLabel").live("keyup",function(){
            value = $(this).val();
            $("#"+label_id).text(value);
        });
        
        //for change the field size
        $(".fieldsize").live("change",function(){
            fieldSize_value = $(this).val();
            fz_id = $(".fieldsize :selected").attr("id");
            $("."+object).attr("fieldsize_selected",fz_id);
            $("."+object).removeClass("input-xlarge");  // remove ".input-xlarge" class
            //animate the size of object depending on value of fieldSize_value
            $("."+object).animate({
                "width":fieldSize_value+"%"
                });
        });
        //for change the field layout
        $(".fieldlayout").live("change",function(){
            flayout_id = $(".fieldlayout :selected").attr("id")
            $("."+object).attr("flayout_id",flayout_id);
            $(".choices_li"+master_id).each(function(){
                $(this).removeClass("choicesDefCol");
                $(this).removeClass("choicesTwoCol");
                $(this).removeClass("choicesThreeCol");
                $(this).addClass(flayout_id)
            })
            
        });
        //for options change ex. admin or user and admin
        $(".radio_options").live("change",function(){
            showFieldObject_id = $(this).attr("id");
            $("."+object).attr("showFieldObject_id",showFieldObject_id)
        });
        //for name format
        $(".radio_nf").live("click",function(){
            value_nf = $(this).val();
            nf_id = $(this).attr("id")
            if(value_nf=="nf_full"){
                //alert("full")
                $(".standard_fn"+master_id).fadeIn()
            }else if(value_nf=="nf_standard"){
                //alert("standard")
                $(".standard_fn"+master_id).fadeOut()
            }
            $("."+object).attr("nf_id",nf_id)
        });
        //for required or not
        $("#required_chk").live("change",function(){
            require_check = $(this).attr("checked");
            if(require_check==null){
                check_status = 0;
                $("#req_obj"+master_id).text("")
            }else{
                check_status = 1;
                $("#req_obj"+master_id).text("*")
            }
            $("."+object).attr("require_check",check_status);
        });
        //variable for appending the object for field settings tab
        //dynamic field for field settings tab
        //"NOT" for checkbox, radio, linebreak, fullname, fulladdress
        flabel_value = $("#label"+master_id).text();
        flabel = "<label id='labelObject' class='fontGray'>Field Label:</label>"+ //label for field label
                    "<textarea class='fieldLabel'>"+flabel_value+"</textarea>"; //input for field label
        
        if(objectType=="checkbox" ||
            objectType=="radio" ||
            objectType=="linebreak" ||
            objectType=="fullname" ||
            objectType=="fulladdress" ||
            objectType=="richtext"){
        }else{
            fz = "<label id='labelObject' class='fontGray'>Field Size:</label>"+ //label for field size
                    "<select class='fieldsize'>"+ //options for field size
                    "<option id='fz_default' value=''>-Field Size-</option>"+
                    "<option id='fz_small' value='30'>Small</option>"+
                    "<option id='fz_medium' value='35'>Medium</option>"+
                    "<option id='fz_large' value='43'>Large</option>"+
                    "<option id='fz_long' value='90'>Long</option>"+
                "</select>";
        }
        //for checkbox and radio field layout
        if(objectType=="checkbox" || objectType=="radio" ){
            flayout = "<label id='labelObject' class='fontGray'>Field Layout:</label>"+ //label for field layout
                        "<select class='fieldlayout'>"+ //options for field size
                        "<option id='choicesDefCol' value='choicesDefCol'>One Column</option>"+
                        "<option id='choicesTwoCol' value='choicesTwoCol'>Two Columns</option>"+
                        "<option id='choicesThreeCol' value='choicesThreeCol'>Three Columns</option>"+
                    "</select>";
        }
        //for checkbox, radio, dropdown and selectmany add of choices
        if(objectType=="checkbox" || objectType=="radio" || objectType=="dropdown" || objectType=="selectmany"){
            objAppendType = "";
            if(objectType=="checkbox" || objectType=="selectmany" ){
                objAppendType = "checkbox";    
            }else{
                objAppendType = "radio";
            }
            ctrForCheckbox=0;
            plusminusSign = "<i class='icon-plus-sign' id='plus'></i>&nbsp;&nbsp;"; //default value for plusminusSign variable
            choices = "<label id='labelObject' class='fontGray'>Choices (?):</label>"; //choices label
            
            //append of choices
            $(".objectsChoices"+master_id).each(function(){
                full_child_id = $(this).attr("child-id");
                checked = "";
                child_id = full_child_id.substr(10,full_child_id.length);
                if(objectType=="selectmany" || objectType=="dropdown"){
                    valueText = $(this).text();
                    if($(this).attr("selected")!=null){
                        checked = "checked='checked'";
                    }
                }else{
                    valueText = $(this).next().text();
                    if($(this).attr("checked")!=null){
                        checked = "checked='checked'";
                    }
                }
                if(ctrForCheckbox>0){
                    plusminusSign = "<i class='icon-plus-sign' id='plus'></i>&nbsp;&nbsp;"+
                                    "<i class='icon-minus-sign' id='minus'></i>";
                }
                ctrForCheckbox++;
                choices+= "<div class='formRadio divRadio"+child_id+"'>"+
                        "<input type='"+objAppendType+"' class='"+objAppendType+" choicesObject' "+checked+" id='choicesObject"+child_id+"' name='"+objAppendType+"'></div>"+
                        "<input type='text' class='choicesLabel' id='choices"+child_id+"' value='"+valueText+"' />"+
                        "<span class='fornav' id='fornav"+child_id+"'>"+
                            plusminusSign+
                        "</span><br id='br"+child_id+"'/>";
                
            }); // end of each function or loop
        }
        // for all field or objecs
        // sfo = Show Field Object
        options = "<div class='row-fluid' >"+
                    "<div class='span5'>"+
                        "<label id='labelObject' class='fontGray'>Options:</label>"+
                        "<label id='checkbox' class='checkbox'>"+
                          "<input type='checkbox' id='required_chk'> Required"+
                        "</label>"+
                    "</div>"+
                    "<div class='span5'>"+
                        "<label id='labelObject' class='fontGray'>Show field to:</label>"+
                        "<label id='radio' class='radio'>"+
                        "<input type='radio' class='radio_options' id='sfo_1' checked='checked' value='1' name='radio_option'> Everyone"+
                        "</label>"+
                        "<label id='radio' class='radio'>"+
                          "<input type='radio' class='radio_options' id='sfo_2' value='2' name='radio_option'> Admin Only"+
                        "</label>"+
                    "</div>"+
                "</div>";
        /*for fullname
        for name format options
        nf = name format */
        if(objectType=="fullname"){
            nf =    "<div class='row-fluid' >"+
                      "<div class='span5'>"+
                            "<label id='labelObject' class='fontGray'>Name Format:</label>"+
                            "<label id='radio' class='radio'>"+
                            "<input type='radio' class='radio_nf' id='nf_1' checked='checked' value='nf_full' name='radio_nf'> Full Name"+
                            "</label>"+
                            "<label id='radio' class='radio'>"+
                              "<input type='radio' class='radio_nf' id='nf_2' value='nf_standard' name='radio_nf'> Standard"+
                            "</label>"+
                        "</div>"+
                    "</div>";
        }
        /*for line break
        lb_desc = line break description
        */
        lb_desc_val = $(".linebreak"+master_id).text();
        if(objectType=="linebreak"){
            lb_desc="<label id='labelObject' class='fontGray'>Description:</label>"+ //label for field label
                    "<textarea class='lb_desc' lb_id = '"+master_id+"'>"+lb_desc_val+"</textarea>";
        }
        /*for full address
        pdc = pre define country
        */
        if(objectType=="fulladdress"){
            //wala pa?? or wala na neto!
        }
        //append the object for field settings tab
        $("#tab2").html(flabel + // field label
                lb_desc + //line break description
                fz + // field size
                flayout + //layout
                nf + // name format
                choices +// for radio and checkbox
                options);
        
        //for fieldsize to be selected
        if(fieldsize_selected!=null){
            $(".fieldsize").find("#"+fieldsize_selected).attr("selected","selected")
        }
        if(flayout_var!=null){
            $(".fieldlayout").find("#"+flayout_var).attr("selected","selected")
        }
        //for field option to be viewed by either admin only or user and admin
        if(showFieldObject_id!=null){
            $("#"+showFieldObject_id).attr("checked","checked")
        }
        // for require options
        if(require_check!=null){
            if(require_check==1){
                //checked
                $("#required_chk").attr("checked","checked");
            }else{
                //unchecked
                $("#required_chk").attr("checked",false);
            }
        }
        //for name format
        if(nameFormat_id!=null){
            $("#"+nameFormat_id).attr("checked","checked")
        }
    }); //end of object click
    
    //click the header of the form and change the tab to form settings
    $(".setObjectForm").live("click",function(){
        $(".field_settings").html("<h6>No Object is selected </h6>");
        //activating the form header
        $("#"+this.id).css({
            "background-color":"#b7ffb7"
            });
        $("#"+this.id).removeClass("borderDashed");
        //deactivating the objects
        $(".setObject").each(function(){
            //changing the css
            $("#"+this.id).css({
                "background-color":"#FFF"
            })
            //add class for having a border dashed on hover
            $("#"+this.id).addClass("borderDashed");
        })
        //activate the formsetting tab
        $(".addfield").removeClass("active");
        $(".formsetting").addClass("active");
        $(".fieldsettings").removeClass("active");
        $(".workflowSettings").removeClass("active");
        $(".formList").removeClass("active");
        //for update
        $(".formList").removeClass("active");
        $(".editAddfield").removeClass("active")
        $(".editFieldsetting").removeClass("active")
        $(".editFormsetting").addClass("active");
        $(".formName").val($(".formTitleText").text());
        $(".formDesc").val($(".formDescText").text());
        alignForm = $(".formTitleText").attr("align");
        $("#allign"+alignForm).attr("selected","selected")
    });
    
    //for change the form title
    $(".formName").live("keyup",function(){
        value = $(this).val();
        if(value==""){
            $(".formTitleText").text("Untitled Form");
        }else{
            $(".formTitleText").text(value);
        }
    });
    //change description of line break
    $(".lb_desc").live("keyup",function(){
        value = $(this).val();
        lb_id = $(this).attr("lb_id")
        $(".linebreak"+lb_id).text(value);
    })
    //add selection for radio, checkbox, dropdown, selectmany
    $("#plus").live("click",function(){
        classAppendto = $(this).parent().attr("id");
        child_id = classAppendto.substr(6,classAppendto.length);
        objAppendType = "";
        choicesCol = $(".checkbox"+master_id).attr("flayout_id");
        if(objectType=="checkbox" || objectType=="selectmany"){
            objAppendType = "checkbox"; 
        }else{
            objAppendType = "radio";
        }
        $("<div class='formRadio  divRadio"+startIdOfAppend+"'>"+
                        "<input type='"+objAppendType+"' class='"+objAppendType+" choicesObject' id='choicesObject"+startIdOfAppend+"' name='"+objAppendType+"' name='radio'></div>"+
                        "<input type='text' class='choicesLabel' id='choices"+startIdOfAppend+"' value='Default' />"+
                        "<span class='fornav' id='fornav"+startIdOfAppend+"'>"+
                            "<i class='icon-plus-sign' id='plus'></i>&nbsp;&nbsp;"+
                            "<i class='icon-minus-sign' id='minus'></i>"+
                        "</span><br id=br"+startIdOfAppend+"> / ").insertAfter("#br"+child_id);
        
        if(objectType=="selectmany"){
            $("<option class='objectsChoices"+master_id+" selectMany"+startIdOfAppend+""+master_id+"' child-id='checkChild"+startIdOfAppend+"'>Default</option>").insertAfter(".selectMany"+child_id+master_id);
        }else if(objectType=="dropdown"){
            $("<option class='objectsChoices"+master_id+" dropdown"+startIdOfAppend+""+master_id+" dropdownObject"+master_id+"' child-id='checkChild"+startIdOfAppend+"' id='dropdown"+startIdOfAppend+""+master_id+"'>Default</option>").insertAfter(".dropdown"+child_id+master_id);
        }else if(objectType=="radio"){
            $("<li class='"+ choicesCol +" choices_li"+master_id+" radioparentlist"+startIdOfAppend+master_id+"'><label id='"+objectType+"' class='checkboxparent"+startIdOfAppend+""+master_id+"'>"+
                    "<input type='"+objectType+"' class='objectsChoices"+master_id+" checkbox"+startIdOfAppend+""+master_id+" radioObject"+master_id+"' child-id='checkChild"+startIdOfAppend+"' id='radioObject"+startIdOfAppend+""+master_id+"' style='margin-top:-3px;'>"+
                    "<span class='checkboxlabel"+startIdOfAppend+""+master_id+"' style='margin-left:10px;'>Default</span>"+
                    "</label>").insertAfter(".radioparentlist"+child_id+master_id);
        }else{
            $("<li class='"+ choicesCol +" choices_li"+master_id+" checkboxparentlist"+startIdOfAppend+master_id+"'><label id='"+objectType+"' class='checkboxparent"+startIdOfAppend+""+master_id+"'>"+
                    "<input type='"+objectType+"' class='objectsChoices"+master_id+" checkbox"+startIdOfAppend+""+master_id+"' child-id='checkChild"+startIdOfAppend+"' id='checkbox"+startIdOfAppend+""+master_id+"' style='margin-top:-3px;'>"+
                    "<span class='checkboxlabel"+startIdOfAppend+""+master_id+"' style='margin-left:10px;'>Default</span>"+
                    "</label></li>").insertAfter(".checkboxparentlist"+child_id+master_id);
        }
        startIdOfAppend++;
    });
    //label choices of radio, checkbox, dropdown and selectmany
    $(".choicesLabel").live("keyup",function(){
        full_id = $(this).attr("id");
        value = $(this).val();
        id = full_id.substr(7,full_id.length);
        if(objectType=="checkbox"){
            $(".checkboxlabel"+id+master_id).text(value)
        }else if(objectType=="radio"){
            $(".checkboxlabel"+id+master_id).text(value)
        }else if(objectType=="selectmany"){
            $(".selectMany"+id+master_id).text(value)
        }else if(objectType=="dropdown"){
            $(".dropdown"+id+master_id).text(value)
        }
    });
    //for activate the object
    $(".choicesObject").live("click",function(){
        full_id = $(this).attr("id");
        id = full_id.substr(13,full_id.length);
        if(objectType=="checkbox"){
            if($(this).attr("checked") == null){
                $(".checkbox"+id+master_id).attr("checked",false)
            }else{
                $(".checkbox"+id+master_id).attr("checked","checked")
            }   
        }else if(objectType=="radio"){
            $(".radioObject"+master_id).each(function(){
                if(this.id=="radioObject"+id+""+master_id+""){
                    $("#"+this.id).attr("checked","checked")
                }else{
                    $("#"+this.id).removeAttr("checked")
                }
            })
        }else if(objectType=="selectmany"){
            if($(this).attr("checked") != null){
                $(".selectMany"+id+master_id).attr("selected","selected");
            }else{
                $(".selectMany"+id+master_id).removeAttr("selected");
            } 
        }else if(objectType=="dropdown"){
            $(".dropdownObject"+master_id).each(function(){
                if(this.id=="dropdown"+id+""+master_id+""){
                    $("#"+this.id).attr("selected","selected")
                }else{
                    $("#"+this.id).removeAttr("selected")
                }
            })
        }
    });
    //delete selection for radio and checkbox
    $("#minus").live("click",function(){
        Removeclass = $(this).parent().attr("id");
        id = Removeclass.substr(6,Removeclass.length);
        $(".divRadio"+id).remove(); // Radio Button
        $("#choices"+id).remove(); // Radio Textfield label
        $("#fornav"+id).remove(); // Radio icon (+, -)
        $("#br"+id).remove();
        if(objectType=="dropdown"){
            $(".dropdown"+id+master_id).remove();
        }else if(objectType=="selectmany"){
            $(".selectMany"+id+master_id).remove();
        }else{
            $(".checkboxparent"+id+master_id).remove();
        }
        
    });
    //change the position of the header
    $("#formLabelAlign").live("change",function(){
        value = $(this).val();
        $(".formTitleText").attr("align",value);
        $(".setObjectForm").css("text-align",value);
    });
    //for change the form description
    $(".formDesc").live("keyup",function(){
        value = $(this).val();
        $(".formDescText").text(value);
    });
    //form settings
    $(".formsetting").live("click",function(){
        //activate the form header
        $("#head").css({
            "background-color":"#b7ffb7"
        });
        //clear the objects of field settgins
        $(".field_settings").html("<h6>No Object is selected </h6>");
        //deactivate the objects
        $(".setObject").each(function(){
                $("#"+this.id).css({
                    "background-color":"#FFF"
                })
        });
    });
    $(".formList").live("click",function(){
        $(".forForm").show();
    })
    //2 field settings tab to deactivate form header
    $(".field_s").live("click",function(){
        $("#head").css({
            "background-color":"#FFF"
        });
    });
    $(".form_s").live("click",function(){
        $(".forForm").show();
        $(".main_container").hide();
        $(".update_container").hide();
        //$(".saveEdit_forms").hide();
    })
    $(".workflowSettings").live("click",function(){
        $(".editFormContent").hide();
        $(".forForm").hide();
        $(".main_container").show();
        $(".update_container").hide();
        ////
        $(".labelElement").each(function(){
          $(".formLabels").append("<option>"+$(this).text()+"</option>")  
        })
        //$(".saveEdit_forms").hide();
        //$(".save_form").hide();
    })
    //reset the main container
    $(".reset").live("click",function(){
        $(".mainContent").html("<br>")
        $(".field_settings").html("<h6>No Object is selected </h6>");
        $(".setObjectForm").css({
            "background-color":"#FFF"
        });
    });
    $(".close").live("click",function(event){
        event.stopPropagation();
        event.preventDefault();
        id = this.id.substr(5,this.id.length);
        $("#spanParent"+id).remove();
        $(".field_settings").html("<h6>No Object is selected </h6>");
    })
    $(".save_form").live("click",function(){
        $.post("/ajax/checkRow",{action:"checkOrgChart"},function(checkOrgChart){
            if(checkOrgChart==1){
                //validation for label
                valid = "";
                validLines = false;
                sameLabelCount = 0;
                countElement = 0
                $(".labelElement").each(function(){
                    textOld = $(this).text();
                    $(".labelElement").each(function(){
                        if(textOld==$(this).text()){
                            sameLabelCount++;
                        }
                    })
                    countElement++;
                })
                $(".line").each(function(){
                    if($(this).attr("master_id")=="flowspan_1_worklow"){
                        validLines=true;
                    }
                })
                if(countElement==sameLabelCount){
                    //WORKFLOW
                        //for objects
                        object_id = [];
                        object_tops = [];
                        object_lefts = [];
                        object_role = [];
                        object_status = [];
                        ctrend = 0;
                        $(".appendShapes").each(function(){
                            object_id.push($(this).attr("id"));
                            object_tops.push($(this).css("top"));
                            object_lefts.push($(this).css("left"));
                            textId = $(this).attr("id").split("_");
                            object_status.push($("#spanStatus_"+textId[1]).text());
                            //alert($("#spanStatus_"+textId[1]).text())
                            object_role.push($("#spanText_"+textId[1]).text());
                            if($(this).attr("node-type")=="end"){
                                ctrend++;
                            }
                        })
                        //for lines
                        line_id = [];
                        master_id_workflow = [];
                        child_id = [];
                        line_tops = [];
                        line_lefts = [];
                        line_heights = [];
                        line_widths = [];
                        line_margin_lefts = [];
                        line_margin_tops = [];
                        line_axis = [];
                        line_type = [];
                        $(".line").each(function(){
                            line_id.push($(this).attr("id"));
                            master_id_workflow.push($(this).attr("master_id"));
                            child_id.push($(this).attr("child_id"));
                            line_tops.push($(this).css("top"));
                            line_lefts.push($(this).css("left"));
                            line_heights.push($(this).css("height"));
                            line_widths.push($(this).css("width"));
                            line_margin_tops.push($(this).css("margin-top"));
                            line_margin_lefts.push($(this).css("margin-left"));
                            line_axis.push($(this).attr("axis"));
                            line_type.push($(this).attr("line-type"));
                        })
                    if(line_id.length>0){
                        valid = true;
                    }
                    userForm = [];
                    ctrChecked = 0;
                    if($(".allUsers").attr("checked")=="checked"){
                        ctrChecked++;
                        //alert($(".allUsers").val())
                        userForm.push($(".allUsers").val())
                    }else{
                        $(".usersForm").each(function(){
                            if($(this).attr("checked")){
                                ctrChecked++;
                                userForm.push($(this).val())
                            }
                        })    
                    }
                    //separator (`)
                    //for header pattern(align`formtext`)
                    
                    formHeader = $(".formTitleText").text()+"`"+$(".formDescText").text()+"`"+$(".formTitleText").attr("align");
                    objects = "";
                    objectType = "";
                    label = [];
                    options = [];
                    sft = [];
                    fieldsize = [];
                    fieldlayout = [];
                    choices = "";
                    choicesPush = [];
                    name_format = [];
                    fof = [];
                    ftu = [];
                    objectType_array = [];
                    lb_desc_arr = [];
                    confRequest = $(".confRequest").val();
                    if($(".setObject").html()!=null && valid==true && ctrChecked>0 && confRequest!=0){
                        if(ctrend==0){
                            showNotification({
                                message: "Please End your workflow",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        }else if(ctrend==1){
                                $(".setObject").each(function(){
                                object = $(this).attr("object-identifier");
                                master_id = $(this).attr("master-id"); //master id
                                objectType = $(this).attr("object-type"); //field or object type
                                label.push($("#label"+master_id).text()); //label for fields
                                options.push($("."+object).attr("require_check")); //options if required
                                sft.push($("."+object).attr("showfieldobject_id")); //show field to?
                                fof.push($("."+object).attr("fof"));
                                ftu.push($("."+object).attr("ftu"));
                                objectType_array.push($(this).attr("object-type"));
                                if(objectType=="fullname"){
                                    name_format.push($("."+object).attr("nf_id"));
                                }else{
                                    name_format.push(0);
                                }
                                //line break description(for line break only)
                                if(objectType=="linebreak"){
                                    lb_desc_arr.push($(".linebreak"+master_id).text());
                                }else{
                                    lb_desc_arr.push(0)
                                }
                                //field size (for selected fields only)
                                if(objectType=="checkbox" ||
                                    objectType=="radio" ||
                                    objectType=="linebreak" ||
                                    objectType=="fullname" ||
                                    objectType=="fulladdress"){
                                    fieldsize.push(0)
                                }else{
                                    if($("."+object).attr("fieldsize_selected")!=null){
                                        fieldsize.push($("."+object).attr("fieldsize_selected"));
                                    }else{
                                        fieldsize.push("fz_large"); //default field size (for selected fields only)
                                    }
                                }
                                //field layout (for selected fields only)
                                if(objectType=="checkbox" || objectType=="radio" ){
                                    fieldlayout.push($("."+object).attr("flayout_id"));
                                }else{
                                    fieldlayout.push(0);
                                }
                                //for checkbox, radio, dropdown and selectmany choices
                                if(objectType=="checkbox" || objectType=="radio" || objectType=="dropdown" || objectType=="selectmany"){
                                    $(".objectsChoices"+master_id).each(function(){
                                        if(objectType=="checkbox" || objectType=="radio"){
                                            choicesText = $(this).next().text();
                                            if($(this).attr("checked")!=null){
                                                choices+=choicesText+":1`";
                                            }else{
                                                choices+=choicesText+":0`";
                                            }
                                        }else{
                                        choicesText = $(this).text();
                                            if($(this).attr("selected")!=null){
                                                choices+=choicesText+":1`";
                                            }else{
                                                choices+=choicesText+":0`";
                                            }
                                        }
                                    })
                                    choicesPush.push(choices);
                                }else{
                                    choicesPush.push(0);
                                }
                            })
                            $.post("/ajax/saveObject/",{"confAddForm":1},function(data){
                                if(data=="1"){
                                    if(validLines==true){
                                        //ajax post to save on database
                                        $.post("/ajax/saveWorkFlow",{action:"validateWorkflow","object_id[]":[object_id],"line_id[]":[line_id]},function(valid){
                                            if(valid==1){
                                            conf = confirm("Are you sure with this form?");
                                            if(conf){
                                                //FOR FORM
                                                $.post("/ajax/saveObject/",{formHeader:formHeader,
                                                       "label[]":[label],
                                                       "options[]":[options],
                                                       "sft[]":[sft],
                                                       "fieldsize[]":[fieldsize],
                                                       "fieldlayout[]":[fieldlayout],
                                                       "choicesPush[]":[choicesPush],
                                                       "name_format[]":[name_format],
                                                       "objectType_array[]":[objectType_array],
                                                       "fof[]":[fof],
                                                       "ftu[]":[ftu],
                                                       "lb_desc_arr[]":[lb_desc_arr],
                                                       "addform":"addform",
                                                       "userForm[]":[userForm],
                                                       },function(form_id){
                                                        //alert(form_id)
                                                        //FOR wORKFLOW
                                                        if(form_id!=0){
                                                            $.post("/ajax/saveWorkFlow",{action:"saveWorkFlow",
                                                                        "object_id[]":[object_id],
                                                                        "object_tops[]":[object_tops],
                                                                        "object_lefts[]":[object_lefts],
                                                                        "object_role[]":[object_role],
                                                                        "object_status[]":[object_status],
                                                                        "line_id[]":[line_id],
                                                                        "master_id_workflow[]":[master_id_workflow],
                                                                        "child_id[]":[child_id],
                                                                        "line_tops[]":[line_tops],
                                                                        "line_lefts[]":[line_lefts],
                                                                        "line_heights[]":[line_heights],
                                                                        "line_widths[]":[line_widths],
                                                                        "line_margin_lefts[]":[line_margin_lefts],
                                                                        "line_margin_tops[]":[line_margin_tops],
                                                                        "line_axis[]":[line_axis],
                                                                        "line_type[]":[line_type],
                                                                        form_id:form_id,
                                                                        confRequest:confRequest
                                                                        },function(data){
                                                                            //alert(data)
                                                            });
                                                        }
                                                });
                                                // notification
                                                showNotification({
                                                    message: "Form Saved!",
                                                    type: "success",
                                                    autoClose: true,
                                                    duration: 3
                                                });
                                                //reserve for loading
                                                $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                                                }    
                                            }else{
                                                showNotification({
                                                    message: "Your Workflow has an error",
                                                    type: "error",
                                                    autoClose: true,
                                                    duration: 3
                                                });
                                            }
                                        })
                                    }else{
                                        showNotification({
                                            message: "You MUST connect the start",
                                            type: "error",
                                            autoClose: true,
                                            duration: 3
                                        });
                                        //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                                    }
                                }else{
                                    showNotification({
                                        message: "Your Company form is already 5, Please get our Premium account!",
                                        type: "error",
                                        autoClose: true,
                                        duration: 3
                                    });
                                    //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                                }
                            })
                        }else{
                            showNotification({
                                message: "There's something wrong in your workflow",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        }
                        //FORM
                    }else if($(".setObject").html()==null){
                        showNotification({
                            message: "Create your form",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                    }else if(valid==""){
                        showNotification({
                            message: "Create your workflow",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                    }else if(ctrChecked==0){
                        showNotification({
                            message: "Add User for this form",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                    }else if(confRequest==0){
                    showNotification({
                            message: "Choose status of request",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                    }
                }else{
                    showNotification({
                            message: "Label must be unique",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                }
            }else{
                showNotification({
                    message: "Create first your Organizational Chart",
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
            }
        })
    });
    /*******VIEW FORM***********/
    activeFormForRequest = "";
    $(".formGettitle").live("click",function(){
        master_form_id = this.id;
        form_id = this.id.substr(12,this.id.length)
        activeFormForRequest = form_id;
        $.post("/ajax/setform",{form_id:form_id},function(data){
            $(".formView").html(data);
        })
        $(".formGettitle").each(function(){
            title_id = this.id;
            if(title_id==master_form_id){
                $(this).addClass("activeFormTitle");
            }else{
                $(this).removeClass("activeFormTitle");
            }
        })
    })
    
    
    $(".userManagement").live("click",function(){
        tableClass = $(this).attr("rel");
        $(".userManagement").each(function(){
            if($(this).attr("rel")==tableClass){
                $("."+tableClass).fadeIn("slow");
                $("#"+this.id+" img").attr("src","/images/flowchart/down_arrow.png");
            }else{
                $("."+$(this).attr("rel")).fadeOut("slow");
                $("#"+this.id+" img").attr("src","/images/flowchart/right_arrow.png");
            }
        })
    })
    $(".actionUser").live("click",function(){
        action = $(this).attr("rel");
        userID = this.id;
        messageAction="";
        row_id = $(this).parent().parent().attr("id");
        if(action=="acceptUser"){
            userID = this.id.substr(11,this.id.length);
            roleToInsert = $("#userRole_"+userID).val();
            roleTypeToInsert = $("#userTypeRole_"+userID).val();
            positionToInsert = $(".userPosition :selected").val();
            //alert(positionToInsert)
            if(roleToInsert==0){
                showNotification({
                    message: "Please Select Role!",
                        type: "error",
                   autoClose: true,
                   duration: 3
                });
            }else if(roleTypeToInsert==0){
                showNotification({
                    message: "Please Select Type of Role!",
                        type: "error",
                   autoClose: true,
                   duration: 3
                });
            }else if(positionToInsert==0){
                showNotification({
                    message: "Please Select Position!",
                        type: "error",
                   autoClose: true,
                   duration: 3
                });
            }else{
                $.post("ajax/checkRow",{"action":"checkPositionRow",roleToInsert:roleToInsert,roleTypeToInsert:roleTypeToInsert}, function(data){
                    if(data=="doNotAccept"){
                        showNotification({
                            message: "This department already have a "+roleTypeFunct(roleTypeToInsert),
                                type: "error",
                           autoClose: true,
                           duration: 3
                        });
                    }else{
                        conf = confirm("Do you want to continue this action?");
                        if(conf){
                            $.post("/ajax/actionUser",{action:action,userID:userID,roleToInsert:roleToInsert,roleTypeToInsert:roleTypeToInsert,positionToInsert:positionToInsert},function(data){
                                if(data=="accepted"){
                                    showNotification({
                                        message: "User has been Accepted!",
                                            type: "success",
                                       autoClose: true,
                                       duration: 3
                                    });
                                    //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                                    $.post("/ajax/checkRow",{action:"regUser"},function(data){
                                        $("#"+row_id).fadeOut();
                                        if(data==0){
                                            $(".userRegRequest").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                                        }
                                    })
                                }
                            })     
                        }
                    }
                }) 
            }
        }else if(action=="editUser"){
            id = this.id.substr(9,this.id.length);
            $(this).hide();
            $("#saveEditUser_"+id).show();
            $("#cancelEditUser_"+id).show();
            $("#spanRole_"+id).hide();
            $("#userRoleEdit_"+id).show()
            $("#spanRoleTypeEdit_"+id).hide();
            $("#userTypeRoleEdit_"+id).show();
            $("#spanPositionEdit_"+id).hide();
            $("#userPosition_"+id).show();
            /*$(".editUser").hide();
            $(".saveEditUser").show();
            $(".spanRole").hide();
            $(".userRoleEdit").show();*/
        }else if(action=="saveEditUser"){
            id = this.id.substr(13,this.id.length);
            roleToInsert = $("#userRoleEdit_"+id).val();
            roleTypeToInsert = $("#userTypeRoleEdit_"+id).val();
            roleTypeToInsertText = $("#userTypeRoleEdit_"+id+" :selected").attr("text");
            positionToInsertText = $("#userPosition_"+id+" :selected").text()
            positionToInsertID = $("#userPosition_"+id+" :selected").val()
            conf = confirm("Do you want to continue this action?");
            $.post("ajax/checkRow",{"action":"checkPositionRowEdit",userID:id,roleToInsert:roleToInsert,roleTypeToInsert:roleTypeToInsert}, function(data){
                if(data=="doNotAccept"){
                    showNotification({
                            message: "This department already have a "+roleTypeFunct(roleTypeToInsert),
                                type: "error",
                           autoClose: true,
                           duration: 3
                        });
                }else{
                    if(conf){
                        updateDone = 0;
                        $.post("/ajax/actionUser",{action:"saveEditUser",userID:id,roleToInsert:roleToInsert,roleTypeToInsert:roleTypeToInsert,positionToInsertID:positionToInsertID},function(data){
                            //alert(data)
                            if(data==1){
                                alert(data)
                            }else if(data=="Update Done"){
                                updateDone+=1;
                            }else if(data=="++"){
                                updateDone+=1;
                            }else{
                                alert(data)
                            }
                            if(updateDone>0){
                                showNotification({
                                    message: "User has been Updated!",
                                        type: "success",
                                   autoClose: true,
                                   duration: 3
                                });
                                $("#saveEditUser_"+id).hide();
                                $("#editUser_"+id).show();
                                $("#cancelEditUser_"+id).hide();
                                $("#userRoleEdit_"+id).hide();
                                $("#spanRole_"+id).show();
                                $("#spanRole_"+id).text(roleToInsert);
                                $("#spanRoleTypeEdit_"+id).show();
                                $("#userTypeRoleEdit_"+id).hide();
                                $("#spanRoleTypeEdit_"+id).text(roleTypeToInsertText);
                                $("#spanPositionEdit_"+id).show();
                                $("#userPosition_"+id).hide();
                                $("#spanPositionEdit_"+id).text(positionToInsertText);
                                //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                            }
                        })
                    }
                }
            })
            
        }else if(action=="cancelEditUser"){
            id = this.id.substr(15,this.id.length);
            $("#saveEditUser_"+id).hide();
            $("#saveEditFloatingUser_"+id).hide();
            $("#editUser_"+id).show();
            $("#editFloatingUser_"+id).show();
            $("#cancelEditUser_"+id).hide();
            $("#userRoleEdit_"+id).hide();
            $("#spanRole_"+id).show();
            $("#spanRoleTypeEdit_"+id).show();
            $("#userTypeRoleEdit_"+id).hide();
            $("#spanPositionEdit_"+id).show();
            $("#userPosition_"+id).hide();
        }else if(action=="editFloatingUser"){
            id = this.id.substr(17,this.id.length);
            $(this).hide();
            $("#saveEditFloatingUser_"+id).show();
            $("#cancelEditUser_"+id).show();
            $("#spanRole_"+id).hide();
            $("#userRoleEdit_"+id).show()
        }else if(action=="saveEditFloatingUser"){
            id = this.id.substr(21,this.id.length);
            roleToUpdate = $("#userRoleEdit_"+id+" :selected").val();
            conf = confirm("Do you want to continue this action?");
            if(conf){
                $.post("/ajax/actionUser",{action:"saveEditFloatingUser",userID:id,roleToUpdate:roleToUpdate},function(data){
                    //alert(data)
                    if(data==1){
                        showNotification({
                            message: "User has been Updated!",
                                type: "success",
                           autoClose: true,
                           duration: 3
                        });
                        //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                        $("#saveEditFloatingUser_"+id).hide();
                        $("#editFloatingUser_"+id).show();
                        $("#cancelEditUser_"+id).hide();
                        $("#userRoleEdit_"+id).hide();
                        $("#spanRole_"+id).show();
                        $("#spanRole_"+id).text(roleToUpdate);
                    }
                })
            }
        }else{
            conf = confirm("Do you want to continue this action?");
            if(conf){
                $.post("/ajax/actionUser",{action:action,userID:userID},function(data){
                    if(data=="declined"){
                        messageAction = "User has been Declined!";
                        $.post("/ajax/checkRow",{action:"regUser"},function(data){
                            $("#"+row_id).fadeOut();
                            if(data==0){
                                $(".userRegRequest").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                            }
                        })
                    }else if(data=="deactivated"){
                        messageAction = "User has been Deactivated!";
                        $.post("/ajax/checkRow",{action:"userList"},function(data){
                            $("#"+row_id).fadeOut();
                            if(data==0){
                                $(".listUserBody").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                            }
                        })
                    }else if(data == "restored"){
                        messageAction = "User has been Restored!";
                        $.post("/ajax/checkRow",{action:"deletedAccounts"},function(data){
                            $("#"+row_id).fadeOut();
                            if(data==0){
                                $(".accountsDelBody").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                            }
                        })
                    }else if(data == "deleteUser"){
                        messageAction = "User has been Deleted!";
                        $.post("/ajax/checkRow",{action:"deletedAccounts"},function(data){
                            $("#"+row_id).fadeOut();
                            if(data==0){
                                $(".accountsDelBody").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                            }
                        })
                    }else{
                        alert(data)
                    }
                    /*showNotification({
                        message: messageAction,
                            type: "success",
                       autoClose: true,
                       duration: 3
                    });
                    //$("html").append('<meta http-equiv="refresh" content="2">'); //for refresh*/
                })
            }
        }
    })
    $(".actionUser").tooltip();
    //Administer
    $(".btnAnnouncement").live("click",function(){
        announcement = $(".announcement").val();
        $.post("/ajax/actionAdmin",{action:"updateAnnouncement",announcement:announcement},function(data){
            showNotification({
                message: "Announcement Updated",
                    type: "success",
               autoClose: true,
               duration: 3
            });
            $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
        })
    })
    $(".btnPosition").live("click",function(){
        position = $(".txtPosition").val();
        if(position==""){
           showNotification({
                message: "Position Empty",
                type: "error",
                autoClose: true,
                duration: 3
            }); 
        }else{
            $.post("/ajax/actionAdmin",{action:"addPosition",position:position},function(data){
                if(data==1){
                    showNotification({
                        message: "Position Added",
                            type: "success",
                       autoClose: true,
                       duration: 3
                    });
                    $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                }else if(data==0){
                    showNotification({
                        message: "Position Already in the List",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    }); 
                }else{
                    alert(data)
                }
            })    
        }
    })
    //workflow
    $(".approverTypeWorkflow").live("change",function(){
        value = $(this).val();
        if(value!=0){
            $.post("/ajax/actionAdmin",{action:"getApproverWorflow",value:value},function(data){
                $(".approverWorkflow").html(data);
            })
            $.post("/ajax/actionAdmin",{action:"getStatusWorflow",value:value},function(data){
                $(".statusWorkflow").html(data);
            })
        }else{
            $(".approverWorkflow").html("<option value=0>--Select Approver Type--</option>")
        }
    });
    //view or update form
    form_id = "";
    $(".edit_forms").live("click",function(){
        $(".editAddfield").addClass("active");
        $(".formList").removeClass("active");
        $("#tab0").removeClass("active");
        $("#tab1").addClass("active");
        
        //for html objects
        $.post("/ajax/updateForm",{id:this.id,action:"getFormSettings"},function(data){
            $(".frm_settings").html(data);
        })
        $.post("/ajax/updateForm",{id:this.id,action:"getObjectsToAppend"},function(data){
            $(".add_fields").html(data);
        })
        $.post("/ajax/updateForm",{id:this.id,action:"getobjectId"},function(uniqueid){
            objectId = uniqueid
        })
        $.post("/ajax/updateForm",{id:this.id,action:"getFields"},function(data){
            $(".editFormContent").html(data)
            $( "#drag" ).sortable({
                revert: true,
            });
        })
        $.post("/ajax/updateForm",{id:this.id,action:"getWorkflowSettings"},function(data){
            $(".wf_settings").html(data);
        })
        $.post("/ajax/updateForm",{id:this.id,action:"getWorkflow"},function(data){
            $(".flow_content").html(data);
            moveObjects();
            $(".fl_shapes").css("cursor","pointer");
            $(".connector").draggable({containment:'.flow_content'},{revert: "valid"});
        })
        form_id = this.id
    })
    //edit form status
    //deactivate form
    $(".deact_forms").live("click",function(){
        id = this.id
        conf = confirm("Are you sure to deactivate the form?");
        $.post("/ajax/updateForm",{id:this.id,action:"updateStatusDeactivate"},function(data){
            showNotification({
                message: "Form has been DEACTIVATED",
                type: "success",
                autoClose: true,
                duration: 3
            });
            $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
        })
    })
    //activate form
    $(".activate_forms").live("click",function(){
        id = this.id
        conf = confirm("Are you sure to deactivate the form?");
        $.post("/ajax/updateForm",{id:this.id,action:"updateStatusActivate"},function(data){
            showNotification({
                message: "Form has been ACTIVATED",
                type: "success",
                autoClose: true,
                duration: 3
            });
            $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
        })
    })
    //delete forms 
    $(".delete_forms").live("click",function(){
        id = this.id
        conf = confirm("Are you sure to DELETE the form?");
        $.post("/ajax/updateForm",{id:this.id,action:"deleteForm"},function(data){
            showNotification({
                message: "Form has been DELETED",
                type: "success",
                autoClose: true,
                duration: 3
            });
            $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
        })
    })
    //retrieve form title details
    $(".editFormsetting").live("click",function(){
        $(".formName").val($(".formTitleText").text());
        $(".formDesc").val($(".formDescText").text());
        alignForm = $(".formTitleText").attr("align");
        $("#allign"+alignForm).attr("selected","selected")
    })
    //from edit forms
    $(".saveEdit_forms").live("click",function(){
        //for objects
        object_id = [];
        object_tops = [];
        object_lefts = [];
        object_role = [];
        object_status = [];
        $(".newObj").each(function(){
            object_id.push($(this).attr("id"));
            object_tops.push($(this).css("top"));
            object_lefts.push($(this).css("left"));
            textId = $(this).attr("id").split("_");
            object_role.push($("#spanText_"+textId[1]).text());
            object_status.push($("#spanStatus_"+textId[1]).text())
        })
        //for lines
        line_id = [];
        master_id_workflow = [];
        child_id = [];
        line_tops = [];
        line_lefts = [];
        line_heights = [];
        line_widths = [];
        line_margin_lefts = [];
        line_margin_tops = [];
        line_axis = [];
        line_type = [];
        $(".line").each(function(){
            line_id.push($(this).attr("id"));
            master_id_workflow.push($(this).attr("master_id"));
            child_id.push($(this).attr("child_id"));
            line_tops.push($(this).css("top"));
            line_lefts.push($(this).css("left"));
            line_heights.push($(this).css("height"));
            line_widths.push($(this).css("width"));
            line_margin_tops.push($(this).css("margin-top"));
            line_margin_lefts.push($(this).css("margin-left"));
            line_axis.push($(this).attr("axis"));
            line_type.push($(this).attr("line-type"));
        })
        userForm = [];
        ctrChecked = 0;
        if($(".allUsers").attr("checked")=="checked"){
            ctrChecked++;
            alert($(".allUsers").val())
            userForm.push($(".allUsers").val())
        }else{
            $(".usersForm").each(function(){
                if($(this).attr("checked")){
                    ctrChecked++;
                    alert($(this).val())
                    userForm.push($(this).val())
                }
            })    
        }
        $.post("/ajax/updateForm",{action:"saveUpdatedWorkFlow",
                    "object_id[]":[object_id],
                    "object_tops[]":[object_tops],
                    "object_lefts[]":[object_lefts],
                    "object_role[]":[object_role],
                    "object_status[]":[object_status],
                    "line_id[]":[line_id],
                    "master_id_workflow[]":[master_id_workflow],
                    "child_id[]":[child_id],
                    "line_tops[]":[line_tops],
                    "line_lefts[]":[line_lefts],
                    "line_heights[]":[line_heights],
                    "line_widths[]":[line_widths],
                    "line_margin_lefts[]":[line_margin_lefts],
                    "line_margin_tops[]":[line_margin_tops],
                    "line_axis[]":[line_axis],
                    "line_type[]":[line_type],
                    form_id:form_id
                    },function(data){
                        if(data=="<?>"){
                            showNotification({
                                message: "Invalid Worklow",
                                type: "error",
                                autoClose: true,
                                duration: 3
                            });
                        }else{
                            /*showNotification({
                                message: "Done",
                                type: "success",
                                autoClose: true,
                                duration: 3
                            });*/
                            alert(data)
                        }
        });
        /*
        //separator (`)
        //for header pattern(align`formtext`)
        
        formHeader = $(".formTitleText").text()+"`"+$(".formDescText").text()+"`"+$(".formTitleText").attr("align");
        objects = "";
        objectType = "";
        label = [];
        options = [];
        sft = [];
        fieldsize = [];
        fieldlayout = [];
        choices = "";
        choicesPush = [];
        name_format = [];
        fof = [];
        ftu = [];
        objectType_array = [];
        lb_desc_arr = [];
        if($(".setObject").html()!=null){
            $(".setObject").each(function(){
                object = $(this).attr("object-identifier");
                master_id = $(this).attr("master-id"); //master id
                objectType = $(this).attr("object-type"); //field or object type
                label.push($("#label"+master_id).text()); //label for fields
                options.push($("."+object).attr("require_check")); //options if required
                sft.push($("."+object).attr("showfieldobject_id")); //show field to?
                fof.push($("."+object).attr("fof"));
                ftu.push($("."+object).attr("ftu"));
                objectType_array.push($(this).attr("object-type"));
                if(objectType=="fullname"){
                    name_format.push($("."+object).attr("nf_id"));
                }else{
                    name_format.push(0);
                }
                //line break description(for line break only)
                if(objectType=="linebreak"){
                    lb_desc_arr.push($(".linebreak"+master_id).text());
                }else{
                    lb_desc_arr.push(0)
                }
                //field size (for selected fields only)
                if(objectType=="checkbox" ||
                    objectType=="radio" ||
                    objectType=="linebreak" ||
                    objectType=="fullname" ||
                    objectType=="fulladdress"){
                    fieldsize.push(0)
                }else{
                    if($("."+object).attr("fieldsize_selected")!=null){
                        fieldsize.push($("."+object).attr("fieldsize_selected"));
                    }else{
                        fieldsize.push("fz_large"); //default field size (for selected fields only)
                    }
                }
                //field layout (for selected fields only)
                if(objectType=="checkbox" || objectType=="radio" ){
                    fieldlayout.push($("."+object).attr("flayout_id"));
                }else{
                    fieldlayout.push(0);
                }
                //for checkbox, radio, dropdown and selectmany choices
                if(objectType=="checkbox" || objectType=="radio" || objectType=="dropdown" || objectType=="selectmany"){
                    $(".objectsChoices"+master_id).each(function(){
                        if(objectType=="checkbox" || objectType=="radio"){
                        choicesText = $(this).next().text();
                        }else{
                        choicesText = $(this).text();
                        }
                        if($(this).attr("checked")!=null){
                            choices+=choicesText+":1`";
                        }else{
                            choices+=choicesText+":0`";
                        }
                    })
                    choicesPush.push(choices);
                }else{
                    choicesPush.push(0);
                }
            })
            $.post("/ajax/saveObject/",{"confAddForm":1},function(data){
                if(data=="1"){
                    //ajax post to save on database
                    conf = confirm("Are you sure with this form?");
                    if(conf){
                        $.post("/ajax/updateForm",{formHeader:formHeader,
                               id:form_id,
                               action:"saveEditForm",
                               "label[]":[label],
                               "options[]":[options],
                               "sft[]":[sft],
                               "fieldsize[]":[fieldsize],
                               "fieldlayout[]":[fieldlayout],
                               "choicesPush[]":[choicesPush],
                               "name_format[]":[name_format],
                               "objectType_array[]":[objectType_array],
                               "fof[]":[fof],
                               "ftu[]":[ftu],
                               "lb_desc_arr[]":[lb_desc_arr],
                               "addform":"addform"
                               },function(data){
                                // notification
                                showNotification({
                                    message: "Form Saved!",
                                    type: "success",
                                    autoClose: true,
                                    duration: 3
                                });
                                //reserve for loading
                                $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                        });
                    }
                }else{
                    showNotification({
                        message: "Your Company form is already 5, Please get our Premium account!",
                        type: "error",
                        autoClose: true,
                        duration: 3
                    });
                    $("html").append('<meta http-equiv="refresh" content="2">'); //for refresh
                }
            })
        }else{
            alert("No Object Found")
        }
        */
    })
    $(".saveUserForm").live("click",function(){
        //conf = confirm("Are you sure with this data?");
            arrayData = [];
            countRequired = 0;
            validEmail = 0;
            validWebsite = 0;
            $(".fof").each(function(){
                fieldClassification = $(this).attr("rel");
                if(fieldClassification=="text"){
                    //alert("TextBox ID: "+this.id+"\nLabel: "+$("#"+this.id).attr("label")+"\nValue: "+$("#"+this.id).val())
                    field_id = this.id.split("_")[2];
                    value = $("#"+this.id).val();
                    objectType = $(this).attr("object-type");
                    arrayData.push(field_id+"->"+value)
                    if($(this).attr("option_req")==1){
                        if($(this).val()==""){
                            countRequired+=1
                        }
                    }
                    if(objectType=="email"){
                        if(validateEmail($(this).val())==false){
                            validEmail+=1;
                        }
                    }else if(objectType=="website"){
                        if(validateURL($(this).val())==false){
                            validWebsite+=1;
                        }
                    }
                }else if(fieldClassification=="choice"){
                    parent_id = this.id;
                    field_id = parent_id.split("_")[2];
                    values = "";
                    $("."+this.id).each(function(){
                        if($(this).attr("checked")){
                            value = $(this).val();
                            values+=value+"|";
                            //alert("Checkbox ID: "+parent_id+"\nLabel: "+$(this).attr("label")+"\nValue: "+value)
                        }
                    })
                    if($(this).attr("option_req")==1){
                        countChoices = 0;
                        $("."+this.id).each(function(){
                            if($(this).attr("checked")){
                                countChoices ++;
                            }
                        })
                        if(countChoices==0){
                            countRequired+=1
                        }
                    }
                    arrayData.push(field_id+"->"+values)
                }else if(fieldClassification=="drop"){
                    parent_id = this.id;
                    field_id = parent_id.split("_")[2];
                    values = "";
                    $("."+this.id).each(function(){
                        if($(this).attr("selected")){
                            value = $(this).val();
                            values+=value+"|";
                            //alert("Checkbox ID: "+parent_id+"\nLabel: "+$(this).attr("label")+"\nValue: "+value)    
                        }
                    })
                    if($(this).attr("option_req")==1){
                        countChoices = 0;
                        $("."+this.id).each(function(){
                            if($(this).attr("selected")){
                                countChoices ++;
                            }
                        })
                        if(countChoices==0){
                            countRequired+=1
                        }
                    }
                    arrayData.push(field_id+"->"+values)
                }else if(fieldClassification=="special"){
                    parent_id = this.id;
                    field_id = parent_id.split("_")[2];
                    values = "";
                    label = $(this).attr("label");
                    type = $(this).attr("type");
                    $("."+parent_id).each(function(){
                        value = $(this).val();
                        values+=value+"|";
                        //alert("Fullname ID: "+parent_id+"\nLabel: "+label+"\nValue: "+value+"\nChild: "+this.id)    
                    })
                    if($(this).attr("option_req")==1){
                        if(type=="fullname"){
                            //fullname
                            $("."+parent_id).each(function(){
                                if($(this).val()==""){
                                    countRequired+=1
                                }
                            })
                        }else if(type=="address"){
                            //address
                            $("."+parent_id).each(function(){
                                if(!$(this).attr("select")){
                                    if($(this).val()==""){
                                        countRequired+=1
                                    }
                                }else{
                                    //for country
                                }
                            })
                        }
                    }
                    arrayData.push(field_id+"->"+values)
                }
            })
            formvalidateError = 0;
            if(countRequired>0){
                showNotification({
                    message: "Fill out all required fields",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
            }else{
                if(validEmail>0){
                    showNotification({
                        message: "Invalid Email",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    formvalidateError+=1
                }if(validWebsite>0){
                    showNotification({
                        message: "Invalid Website",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                    formvalidateError+=1
                }
                if(formvalidateError==0){
                    //alert(true)
                    //ajax request!
                    $.post("/ajax/saveFormUser",{action:"saveFormUser","arrayData[]":[arrayData],activeFormForRequest:activeFormForRequest},function(data){
                        //insert request process
                        $.post("/ajax/setApprover",{action:"setFirstApprover",request_id:data,form_id:activeFormForRequest},function(data){
                            if(data==1){
                                showNotification({
                                    message: "Request has been sent! Thanks",
                                    type: "succes",
                                    autoClose: true,
                                    duration: 5
                                });
                                $("html").append('<meta http-equiv="refresh" content="3">'); //for refresh    
                            }else{
                                alert(data)
                            }
                        })
                    })
                }
            }
    })
    //end saveUserForm click
    $(".btnAddRole").live("click",function(){
        role = $("#txtRole").val();
        if(role==""){
            showNotification({
                    message: "Role is Empty",
                    type: "error",
                    autoClose: true,
                    duration: 5
                });
        }else{
            $.post("/ajax/actionUser",{action:"addRole",role:role},function(data){
                if(data =="roleExist"){
                    showNotification({
                        message: "Exisiting Role",
                        type: "error",
                        autoClose: true,
                        duration: 5
                    });
                }else{
                    showNotification({
                        message: "Role Inserted",
                        type: "success",
                        autoClose: true,
                        duration: 5
                    });
                    $("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                }
            })
        }
    })
    
    $(".userRoleEditOrgChart").live("change",function(){
        roleToInsert = $(".userRoleEditOrgChart :selected").val();
        activeObject = $(".activeObj").attr("id");
        if(roleToInsert!=0){
            if(activeObject!=undefined){
                textAreaID = $("#"+activeObject).children().attr("id");
                spanID = $("#"+activeObject).children().next().attr("id");
                $("#"+textAreaID).val(roleToInsert);
                $("#"+spanID).text(roleToInsert);
                //alert(textAreaID)
            }else{
                alert("Choose 1 node")
            }    
        }
    })
    //captcha login
    $('img#captcha-refresh').live("click",function() {
        $(".captcha").attr("src","/ajax/get_captcha?rnd="+Math.random())
    });
    
    //real time count of user registration
    jQuery(function($){
        oldRowCount = "";
        setInterval(function(){
          $.post("ajax/checkRow",{"action":"regUser"}, function(newRowCount){
            if(newRowCount>0){
                if(oldRowCount!=newRowCount){
                    $(".noti-user").css("display","inline-block");
                    $(".noti-user").text(newRowCount);
                    //$("title").append("("+newRowCount+")")
                }
                oldRowCount = newRowCount;
            }
            
          });
        },1000); // 5000ms == 5 seconds
    });
    
    //User Request Actions
    $(".actionUserRequest").live("click",function(){
        action = $(this).attr("rel");
        if(action=="Open File"){
            general_id = this.id.split("_");
            request_id = general_id[1];
            requestProcess_id = general_id[2];
            $.post("/ajax/openForm",{action:"getFormTitle",request_id:request_id},function(formTitle){
                $(".viewFormHeader").html(formTitle)
            })
            $.post("/ajax/openForm",{action:"getFormData",request_id:request_id},function(formData){
                $(".viewFormBody").html(formData)
                //alert(formData)
            })
        }else{
            conf = confirm("Are you sure to "+action+" this request?");
            dataNumCol = $(this).attr("data-num-col") + parseInt(5);
            row_id = $(this).parent().parent().attr("id");
            if(conf){
            request_id = [];
            requestProcess_id = [];
            nextMaster_id = [];
                if(action=="acceptMany"){
                    //alert(action)
                    countChecked = 0;
                    $(".chkReqApp").each(function(){
                        if($(this).attr("checked")){
                            rows_id = $(this).parent().parent().attr("id");
                            general_id = this.id.split("_");
                            request_id.push(general_id[1]);
                            requestProcess_id.push(general_id[2]);
                            nextMaster_id.push($(this).attr("object-id"));
                            countChecked++;
                            $("#"+rows_id).fadeOut();
                        }
                    })
                    if(countChecked>0){
                        $.post("/ajax/setApprover",{action:"setNextApprover",
                                nextMaster_id:nextMaster_id,
                                request_id:request_id,
                                requestProcess_id:requestProcess_id},function(data){
                             //alert(data)
                             showNotification({
                                message: "Request Approved!",
                                type: "succes",
                                autoClose: true,
                                duration: 5
                            });
                            //$("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                            
                        })    
                    }else{
                       showNotification({
                            message: "Check atleast 1 line",
                            type: "error",
                            autoClose: true,
                            duration: 5
                        }); 
                    }
                }else if(action=="accept"){
                    general_id = this.id.split("_");
                    request_id.push(general_id[1]);
                    requestProcess_id.push(general_id[2]);
                    nextMaster_id.push($(this).attr("object-id"));
                    $.post("/ajax/setApprover",{action:"setNextApprover",
                           nextMaster_id:nextMaster_id,
                           request_id:request_id,
                           requestProcess_id:requestProcess_id},function(data){
                            //alert(data)
                            showNotification({
                                message: "Request Approved!",
                                type: "succes",
                                autoClose: true,
                                duration: 5
                            });
                            //$("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                            
                    })
                    $("#"+row_id).fadeOut();
                    /*$.post("/ajax/checkRow",{action:"requestToApprove"},function(data){
                        alert(data)
                        $("#"+row_id).fadeOut();
                        if(data==0){
                            $(".requestToApproveBody").html('<tr><td colspan="'+dataNumCol+'" style="text-align:center">No Record Found</td></tr>');
                        }
                    })*/
                }else if(action=="rejectMany"){
                    //alert(action)
                    countChecked = 0;
                    $(".chkReqApp").each(function(){
                        if($(this).attr("checked")){
                            rows_id = $(this).parent().parent().attr("id");
                            general_id = this.id.split("_");
                            request_id.push(general_id[1]);
                            requestProcess_id.push(general_id[2]);
                            countChecked++;
                            $("#"+rows_id).fadeOut();
                        }
                    })
                    if(countChecked>0){
                        $.post("/ajax/setApprover",{action:"rejectRequest",
                                request_id:request_id,
                                requestProcess_id:requestProcess_id},function(data){
                             //alert(data)
                             showNotification({
                                message: "Request Rejected!",
                                type: "succes",
                                autoClose: true,
                                duration: 5
                            });
                            //$("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                            
                        })    
                    }else{
                       showNotification({
                            message: "Check atleast 1 line",
                            type: "error",
                            autoClose: true,
                            duration: 5
                        }); 
                    }
                }else if(action=="reject"){
                    general_id = this.id.split("_");
                    request_id.push(general_id[1]);
                    requestProcess_id.push(general_id[2]);
                    $.post("/ajax/setApprover",{action:"rejectRequest",
                           request_id:request_id,
                           requestProcess_id:requestProcess_id},function(data){
                            showNotification({
                                message: "Request Reject!",
                                type: "succes",
                                autoClose: true,
                                duration: 5
                            });
                            //$("html").append('<meta http-equiv="refresh" content="3">'); //for refresh
                            //alert(data)
                    })
                    $("#"+row_id).fadeOut();
                    /*$.post("/ajax/checkRow",{action:"requestToApprove"},function(data){
                        $("#"+row_id).fadeOut();
                        if(data==0){
                            $(".requestToApproveBody").html('<tr><td colspan="'+dataNumCol+'" style="text-align:center">No Record Found</td></tr>');
                        }
                    })*/
                }else if(action=="cancel"){
                    //$("#"+row_id).fadeOut();
                    //alert("Cancel Request")
                    general_id = this.id.split("_");
                    request_id = general_id[1];
                    $.post("/ajax/setApprover",{action:"cancelRequest",request_id:request_id},function(data){
                        if(data==1){
                            showNotification({
                                message: "Request Cancelled!",
                                type: "succes",
                                autoClose: true,
                                duration: 5
                            });
                        }else{
                            alert(data)
                        }
                    })
                    $.post("/ajax/checkRow",{action:"pendingRequest"},function(data){
                        $("#"+row_id).fadeOut();
                        if(data==0){
                            $(".requestPending").html('<tr><td colspan="6" style="text-align:center">No Record Found</td></tr>');
                        }
                    })
                }else if(action=="remove"){
                    $("#"+row_id).fadeOut();
                }
            }    
        }
    })
    
    //user per form
    $(".formUser").live("click",function(){
        collapseDiv($(this).attr("rel"));
    })
    $(".allUsers").live("click",function(){
        if($(".allUsers").attr("checked")=="checked"){
            $(".usersType").each(function(){
                $(this).attr("checked","checked")
            })
        }else{
            $(".usersType").each(function(){
                $(this).attr("checked",false)
            })
        }
    });
    $(".usersType").live("click",function(){
        totalCount = 0;checkedCount = 0;
        $(".usersType").each(function(){
            if($(this).attr("checked")){
                checkedCount++;
            }
            totalCount++
        })
        if(totalCount==checkedCount){
             $(".allUsers").attr("checked","checked")
        }else{
             $(".allUsers").attr("checked",false)
        }
    });
    //ADMINISTRATOR
    $(".editAdmin").live("click",function(){
        if($(this).attr("rel")=="announcement"){
            alert("edit "+$(this).attr("rel"))
        }else if($(this).attr("rel")=="position"){
            alert("edit "+$(this).attr("rel"))
        }
    })
    $(".activateAdmin").live("click",function(){
        if($(this).attr("rel")=="announcement"){
            //ONLY 1 ACTIVE ANNOUNCEMENT
            alert("activate "+$(this).attr("rel"))
        }else if($(this).attr("rel")=="position"){
            alert("activate "+$(this).attr("rel"))
        }
    })
    $(".deactivateAdmin").live("click",function(){
        if($(this).attr("rel")=="announcement"){
            alert("deactivate "+$(this).attr("rel"))
        }else if($(this).attr("rel")=="position"){
            alert("deactivate "+$(this).attr("rel"))
        }
    })
    $(".deleteAdmin").live("click",function(){
        if($(this).attr("rel")=="announcement"){
            alert("delete "+$(this).attr("rel"))
        }else if($(this).attr("rel")=="position"){
            alert("delete "+$(this).attr("rel"))
        }
    })
    
    $(".getApproverAdminSett").live("change",function(){
        if($(this).val()!=0){
            value = $(this).val();
            type = $(this).attr("rel");
            $.post("/ajax/actionAdmin",{action:"getApproverTypeAdminSett",value:value,type:type},function(data){
                $(".getApproverChoices").show().html(data)
            })
        }else{
            $(".getApproverChoices").hide()
        }
    })
    $(".setapproverAdminSett").live("change",function(){
        if($(this).val()!=0){
            value = $(this).val();
            type = $(this).attr("rel");
            $.post("/ajax/actionAdmin",{action:"getApproverTypeAdminSett",value:value,type:type},function(data){
                $(".setApproverChoices").show().html(data)
            })
        }else{
            $(".setApproverChoices").hide()
        }
    })
    $(".btnUpdateApprover").live("click",function(){
        if($(".getApproverAdminSett").val()!=0 && $(".setapproverAdminSett").val()!=0){
            getUser = "";getUserType = "";
            $(".getAA").each(function(){
                if($(this).attr("rel")=="role"){
                    getUser = $(".roleTypeAdminSettgetAA :selected").val()+"_"+$(".approverTypeAdminSettgetAA :selected").val()
                    getUserType = "1";
                }else if($(this).attr("rel")=="specificUser"){
                    getUser = $(this).val()
                    getUserType = "2";
                }
            })
            setUser = "";setUserType = "";
            $(".setAA").each(function(){
                if($(this).attr("rel")=="role"){
                    setUser = $(".roleTypeAdminSettsetAA :selected").val()+"_"+$(".approverTypeAdminSettsetAA :selected").val()
                    setUserType = "1";
                }else if($(this).attr("rel")=="specificUser"){
                    setUser = $(this).val()
                    setUserType = "2";
                }
            })
            $.post("/ajax/actionAdmin",{action:"moveRequest",getUser:getUser,setUser:setUser,getUserType:getUserType,setUserType:setUserType},function(data){
                if(data==1){
                    showNotification({
                        message: "Pending Request Moved",
                        type: "succes",
                        autoClose: true,
                        duration: 5
                    });
                }else{
                    alert(data)    
                }
                
            })
        }else{
            alert("error")
        }
        
    })
    //ACTION ON REQUEST APPROVAL (CHECKBOX)
    $(".chkReqAppAll").live("click",function(){
        checkUncheck($(this).attr("checked"),"chkReqApp");
    })
    
});
/****System Actions and Others*********/
//Customized Functions
function setActivNav(idOfNav){
    $(".navBar").each(function(){
        if(this.id==idOfNav){
            $("li#"+idOfNav).addClass("icon-arrow-down");
            $("#"+idOfNav).addClass("active-nav");
        }else{
            //$("#"+this.id).removeClass("active");
        }
    })
}
function change_captcha(id)
{
       $(".captcha").attr("src","/ajax/get_captcha?rnd="+Math.random())
}
function validateEmail(email){  
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(email==""){
        return true;
    }else{
        if(email.match(mailformat)){  
            return true;  
        }else{
            return false;  
        }      
    }
}
function validateURL(url){
    var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}
function roleTypeFunct(roleType){
    if(roleType==1){
        return "Head";
    }else if(roleType==2){
        return "Assistant Head";
    }
}

function collapseDiv(collapse){
    $("."+collapse).toggleClass("openCollpase");
    strClass = $("."+collapse).attr("class");
    if(strClass.search("openCollpase")>0){
        $("."+collapse).slideDown();
        $("#"+collapse).removeClass("icon-plus")
        $("#"+collapse).addClass("icon-minus")
    }else{
        $("."+collapse).slideUp();
        $("#"+collapse).removeClass("icon-minus")
        $("#"+collapse).addClass("icon-plus")
    }
}

function checkUncheck(attr,classToEach){    
    if(attr=="checked"){
        $("."+classToEach).each(function(){
            $(this).attr("checked","checked")
        })
    }else{
        $("."+classToEach).each(function(){
            $(this).attr("checked",false)
        })
    }
}
